package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
)

type Send struct {
	d     string
	ip    string
	check bool
}

var sendChan = make(chan Send)
var addhostChan = make(chan string)
var mm = map[string]map[string]Send{}

func init() {
	http.HandleFunc("/api/send", addNewFetch)
	http.HandleFunc("/api/addHost", addHosts)
	http.HandleFunc("/", list)
	http.HandleFunc("/ip", listWithIp)
	go http.ListenAndServe(":22225", nil)

}

func list(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "<head>")
	fmt.Fprintln(w, "<body><ul>")
	for k, _ := range mm {
		//fmt.Fprintf(w, "<li>%s %s <a href='http://192.168.0.50:22225/api/send?d=%s&ip=127.0.0.1'>Block</a></li>", s.ip, s.d, s.d)
		fmt.Fprintf(w, "<li> <a href='/ip?i=%s' target=_blank> %s</a></li>", k, k)
	}
	fmt.Fprintln(w, "</ul></body>")
	fmt.Fprintln(w, "</head>")
}

func listWithIp(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintln(w, "<head>")
	fmt.Fprintln(w, "<body><ul>")
	if m, ok := mm[r.Form.Get("i")]; ok {
		for _, s := range m {
			fmt.Fprintf(w, "<li>%s %s <a target=_blank href='http://192.168.0.50:22225/api/send?d=%s&ip=127.0.0.1'>Block</a></li>", s.ip, s.d, s.d)
			//fmt.Fprintf(w, "<li> <a href='/ip?i=%s' target=_blank> %s</a></li>", k, k)
		}
	}
	fmt.Fprintln(w, "</ul></body>")
	fmt.Fprintln(w, "</head>")
}

func addNewFetch(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	d := r.Form.Get("d")
	ip := r.Form.Get("ip")
	//fmt.Println(d, ip)
	send := new(Send)
	send.d = d
	send.ip = ip
	send.check = false
	sendChan <- *send
}

func addHosts(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	d := r.Form.Get("d")
	ip := r.Form.Get("ip")
	addhostChan <- fmt.Sprintf("%s %s\n", ip, d)
	fmt.Fprintln(w, "success")

}

func cmd(hosts string) {
	if file, err := os.OpenFile("/etc/hosts", os.O_WRONLY|os.O_APPEND, 0666); err == nil {
		defer file.Close()
		file.Write([]byte(hosts))
		cmd := exec.Command("/etc/init.d/dnsmasq restart")
		cmd.Run()

	} else {
		fmt.Println(err)
	}

}
